from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response

from meiduo_admin.serializers.brands_serializer import BrandSerializer
from meiduo_admin.utils import PageNum
from goods.models import Brand


class BrandViewSet(ModelViewSet):
    """
        GoodsChannel表的增删改查
    """
    serializer_class = BrandSerializer
    queryset = Brand.objects.all().order_by('id')
    pagination_class = PageNum

    # 重写拓展类的保存业务逻辑
    def create(self, request, *args, **kwargs):
        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取前端传递的image文件
        data = request.FILES.get('logo')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(data.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id']
        # 获取sku_id
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        if first_letter.length() != 1:
            return Response(status=403)
            # name = request.data.get('name')
        # 保存图片
        img = Brand.objects.create(name=name, logo=image_url, first_letter=first_letter)
        # 返回结果
        return Response(
            {
                'name': img.name,
                'logo': img.logo.url,
                'first_letter': img.first_letter
            },
            status=201  # 前端需要接受201状态
        )

    # 重写拓展类的更新业务逻辑
    def update(self, request, *args, **kwargs):
        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取前端传递的image文件
        data = request.FILES.get('logo')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(data.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id']
        brand = self.get_object()
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        if first_letter.length() != 1:
            return Response(status=403)
            # name = request.data.get('name')
        # 更新图片
        brand.name = name
        brand.first_letter = first_letter
        brand.logo = image_url
        brand.save()
        # 返回结果
        return Response(
            {
                'name': brand.name,
                'logo': brand.logo.url,
                'first_letter': brand.first_letter
            },
            status=201  # 前端需要接受201状态
        )
